package com.toommi.refuse.service.impl;

import com.toommi.refuse.common.util.GsonUtil;
import com.toommi.refuse.service.RedisService;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author yangg
 * @since 2019-07-24 11:26
 */
@Service
@AllArgsConstructor
public class RedisServiceImpl implements RedisService {
    private RedisTemplate redisTemplate;

    @Override
    public void set(String key, Object object) {
        redisTemplate.opsForValue().set(key, GsonUtil.toJson(object));
    }

    @Override
    public void del(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void expire(String key, long seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    @Override
    public Object get(String key, Class className) {
        Object object = redisTemplate.opsForValue().get(key);
        if (object == null) {
            return null;
        }

        try {
            return GsonUtil.fromJson(String.valueOf(object), className);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void refreshKeyExpire(String key) {
        redisTemplate.expire(key, 60*24*60, TimeUnit.SECONDS);
    }

    @Override
    public boolean existKey(String key) {
        return redisTemplate.hasKey(key);
    }
}
